<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input
        v-model="queryParams.title"
        prefix-icon="Search"
        style="width: 240px; margin-right: 10px"
        placeholder="请输入标题查询"
      ></el-input>
      <el-select
        v-model="queryParams.status"
        placeholder="请选择筹款状态"
        style="width: 240px; margin-right: 10px"
      >
        <el-option
          v-for="item in statusList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset"
        >重置</el-button
      >
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table
        stripe
        :data="data.tableData"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="index" label="序号" align="center" width="55" />
        <el-table-column prop="title" label="标题" align="center" />
        <el-table-column prop="cover" label="商品图片">
          <template #default="scope">
            <el-image
              style="width: 50px; height: 50px; border-radius: 5px"
              :src="scope.row.cover"
              :preview-src-list="[scope.row.img]"
              preview-teleported
            ></el-image>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="currentAmount" label="描述" align="center" /> -->
        <el-table-column prop="currentAmount" label="已筹金额" align="center" />
        <el-table-column prop="targetAmount" label="目标金额" align="center" />
        <el-table-column
          label="进度"
          align="center"
          :formatter="
            (row) => (row.currentAmount / row.targetAmount) * 100 + '%'
          "
        />
        <el-table-column
          prop="status"
          label="状态"
          align="center"
          :formatter="statusFormatter"
        />
        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button
              type="primary"
              circle
              :icon="Edit"
              @click="handleEdit(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              circle
              :icon="Delete"
              @click="del(scope.row.projectId)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination
        @current-change="load"
        background
        layout="total, prev, pager, next"
        :page-size="queryParams.pageSize"
        v-model:current-page="queryParams.pageNum"
        :total="data.total"
      />
    </div>

    <el-dialog
      :title="data.title"
      v-model="data.formVisible"
      width="40%"
      destroy-on-close
    >
      <el-form
        ref="form"
        :model="data.form"
        label-width="70px"
        style="padding: 20px"
      >
        <el-form-item prop="title" label="标题">
          <el-input
            v-model="data.form.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="data.form.projectId"
          prop="currentAmount"
          label="已筹金额"
        >
          <el-input
            v-model="data.form.currentAmount"
            placeholder="请输入已筹金额"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item prop="targetAmount" label="目标金额">
          <el-input
            type="number"
            v-model="data.form.targetAmount"
            placeholder="请输入目标金额"
          ></el-input>
        </el-form-item>
        <el-form-item prop="startDate" label="起止时间">
          <el-date-picker
            v-model="data.form.date"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item v-if="data.form.projectId" prop="status" label="状态">
          <el-select v-model="data.form.status" placeholder="请选择筹款状态">
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="cover" label="封面">
          <el-upload
            class="avatar-uploader"
            :action="baseUrl + '/files/upload'"
            :headers="{ token: data.user.token }"
            :on-success="handleFileUpload"
            list-type="picture"
            :show-file-list="false"
          >
            <img v-if="data.form.cover" :src="data.form.cover" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" prop="content">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="data.form.description"
              :mode="mode"
              :defaultConfig="editorConfig"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, toRefs, shallowRef, onBeforeUnmount } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, Plus } from "@element-plus/icons-vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
const data = reactive({
  formVisible: false,
  form: {},
  tableData: [],
  total: 0,
  queryParams: {
    title: "",
    status: "",
    pageNum: 1,
    pageSize: 10,
  },
  title: "",
  user: JSON.parse(localStorage.getItem("xm-user") || "{}"),
});
const { queryParams } = toRefs(data);
const baseUrl = import.meta.env.VITE_BASE_URL;
// 筹款状态
const statusList = [
  { value: "active", label: "筹款中" },
  { value: "completed", label: "完成" },
  { value: "closed", label: "关闭" },
];

// 翻译状态
const statusFormatter = (row) => {
  if (row.status == "active") {
    return "筹款中";
  } else if (row.status == "completed") {
    return "完成";
  } else if (row.status == "closed") {
    return "关闭";
  }
};

onMounted(() => {
  load();
});
const load = async () => {
  const respone = await request.get("/fundraising/selectPage", {
    params: queryParams.value,
  });
  data.tableData = respone.data.list;
  data.total = respone.data.total;
  console.log(data.tableData);
};

const handleEdit = async (row) => {
  data.title = "编辑筹款";
  data.formVisible = true;
  const respone = await request.get("/fundraising/" + row.projectId);
  console.log(respone.data);
  data.form = respone.data;
  data.form.date = [respone.data.startDate, respone.data.endDate];
};

const save = async () => {
  if (data.form.projectId) {
    const respone = await request.put("/fundraising/update", data.form);
    if (respone.code === "200") {
      ElMessage.success("保存成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(respone.msg);
    }
  } else {
    data.form.startDate = data.form.date[0];
    data.form.endDate = data.form.date[1];
    const respone = await request.post("/fundraising/add", data.form);
    if (respone.code === "200") {
      ElMessage.success("添加成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(respone.msg);
    }
  }
};

const handleAdd = () => {
  data.title = "添加筹款";
  data.formVisible = true;
  data.form = {};
};

const handleFileUpload = (res) => {
  data.form.cover = res.data;
};

const del = async (id) => {
  await ElMessageBox.confirm("确认删除？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  const respone = await request.delete("/fundraising/delete/" + id);
  if (respone.code === "200") {
    ElMessage.success("删除成功");
    load();
  } else {
    ElMessage.error(respone.msg);
  }
};

const reset = () => {
  queryParams.value = {
    title: "",
    status: "",
  };
  load();
};

/* wangEditor5 初始化开始 */
const editorRef = shallowRef(); // 编辑器实例，必须用 shallowRef
const mode = "default";
const editorConfig = { MENU_CONF: {} };
// 图片上传配置
editorConfig.MENU_CONF["uploadImage"] = {
  headers: {
    token: data.user.token,
  },
  server: baseUrl + "/files/wang/upload", // 服务端图片上传接口
  fieldName: "file", // 服务端图片上传接口参数
};
// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
// 记录 editor 实例，重要！
const handleCreated = (editor) => {
  editorRef.value = editor;
};
/* wangEditor5 初始化结束 */
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
